package controllers

import (
	"encoding/json"
	"strconv"
	"time"

	"github.com/beego/beego/v2/server/web"

	"supershare/backend/middleware"
	"supershare/backend/models"
)

// RefundController 退款控制器
type RefundController struct {
	web.Controller
}

// URLMapping 路由映射
func (c *RefundController) URLMapping() {
	c.Mapping("GetList", c.GetList)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("Apply", c.Apply)
	c.Mapping("Audit", c.Audit)
	c.Mapping("GetMemberRefunds", c.GetMemberRefunds)
}

// GetMemberRefunds 获取会员退款记录
// @Title Get Member Refunds
// @Description 获取会员退款记录
// @Param	page		query	int	false	"页码"
// @Param	pageSize	query	int	false	"每页数量"
// @Success 200 {object} map[string]interface{}
// @router /member [get]
func (c *RefundController) GetMemberRefunds() {
	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 获取当前登录会员ID
	memberId := c.Ctx.Input.GetData("member_id").(int64)

	// 查询退款记录
	refunds, total, err := models.GetMemberRefunds(memberId, page, pageSize)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取退款记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 构建返回数据
	result := make([]map[string]interface{}, 0)
	for _, refund := range refunds {
		// 格式化时间
		createdAt := time.Unix(refund.CreatedAt, 0).Format("2006-01-02 15:04:05")
		auditTime := ""
		if refund.AuditTime > 0 {
			auditTime = time.Unix(refund.AuditTime, 0).Format("2006-01-02 15:04:05")
		}
		completionTime := ""
		if refund.CompletionTime > 0 {
			completionTime = time.Unix(refund.CompletionTime, 0).Format("2006-01-02 15:04:05")
		}

		item := map[string]interface{}{
			"id":             refund.Id,
			"refundNo":       refund.RefundNo,
			"orderNo":        refund.OrderNo,
			"amount":         refund.Amount,
			"paymentChannel": refund.PaymentChannel,
			"reason":         refund.Reason,
			"status":         refund.Status,
			"auditTime":      auditTime,
			"completionTime": completionTime,
			"createdAt":      createdAt,
		}
		result = append(result, item)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取退款记录成功",
		"data":    result,
		"total":   total,
	}
	c.ServeJSON()
}

// Audit 审核退款
// @Title Audit Refund
// @Description 审核退款
// @Param	body	body	models.RefundAuditForm	true	"退款审核表单"
// @Success 200 {object} map[string]interface{}
// @router /audit [post]
func (c *RefundController) Audit() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var form struct {
		Id     int64  `json:"id"`
		Status string `json:"status"` // approved(通过) 或 rejected(拒绝)
		Remark string `json:"remark"`
	}

	err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if form.Id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的退款ID",
		}
		c.ServeJSON()
		return
	}

	if form.Status != "approved" && form.Status != "rejected" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的审核状态",
		}
		c.ServeJSON()
		return
	}

	// 查询退款记录
	refund, err := models.GetRefundById(form.Id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "退款记录不存在",
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能处理自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		// 查询订单信息以验证加盟商权限
		order, err := models.GetOrderByOrderNo(refund.OrderNo)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无法验证退款关联订单",
			}
			c.ServeJSON()
			return
		}

		// 查询订单所属门店
		store, err := models.GetStoreById(order.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权处理该退款申请",
			}
			c.ServeJSON()
			return
		}
	}

	// 验证退款状态是否为待审核
	if refund.Status != "pending" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该退款申请已审核，无法重复审核",
		}
		c.ServeJSON()
		return
	}

	// 执行审核操作
	err = models.AuditRefund(form.Id, form.Status, permResult.Admin.Id, form.Remark)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "审核退款申请失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 如果审核通过，需要更新订单状态为已退款
	if form.Status == "approved" {
		// 获取订单信息
		order, err := models.GetOrderByOrderNo(refund.OrderNo)
		if err == nil {
			// 更新订单状态为已退款
			_ = models.UpdateOrderStatus(order.Id, 4, "", "system") // 4表示已退款
		}
	}

	// 返回结果
	var message string
	if form.Status == "approved" {
		message = "退款申请已通过"
	} else {
		message = "退款申请已拒绝"
	}

	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": message,
	}
	c.ServeJSON()
}

// GetOne 获取退款详情
// @Title Get Refund Detail
// @Description 获取退款详情
// @Param	id	path	int	true	"退款ID"
// @Success 200 {object} map[string]interface{}
// @router /:id [get]
func (c *RefundController) GetOne() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取退款ID
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的退款ID",
		}
		c.ServeJSON()
		return
	}

	// 查询退款记录
	refund, err := models.GetRefundById(id)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "退款记录不存在",
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		// 查询订单信息以验证加盟商权限
		order, err := models.GetOrderByOrderNo(refund.OrderNo)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无法验证退款关联订单",
			}
			c.ServeJSON()
			return
		}

		// 查询订单所属门店
		store, err := models.GetStoreById(order.StoreId)
		if err != nil || store == nil || store.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权查看该退款记录",
			}
			c.ServeJSON()
			return
		}
	}

	// 获取会员信息
	member, err := models.GetMemberById(refund.MemberId, user.FranchiseId)
	username := ""
	if err == nil {
		username = member.Name
	}

	// 格式化时间
	createdAt := time.Unix(refund.CreatedAt, 0).Format("2006-01-02 15:04:05")
	auditTime := ""
	if refund.AuditTime > 0 {
		auditTime = time.Unix(refund.AuditTime, 0).Format("2006-01-02 15:04:05")
	}
	completionTime := ""
	if refund.CompletionTime > 0 {
		completionTime = time.Unix(refund.CompletionTime, 0).Format("2006-01-02 15:04:05")
	}

	// 构建返回数据
	result := map[string]interface{}{
		"id":             refund.Id,
		"refundNo":       refund.RefundNo,
		"orderNo":        refund.OrderNo,
		"memberId":       refund.MemberId,
		"username":       username,
		"amount":         refund.Amount,
		"paymentChannel": refund.PaymentChannel,
		"transactionId":  refund.TransactionId,
		"refundTradeNo":  refund.RefundTradeNo,
		"reason":         refund.Reason,
		"remark":         refund.Remark,
		"status":         refund.Status,
		"auditTime":      auditTime,
		"auditorId":      refund.AuditorId,
		"completionTime": completionTime,
		"createdAt":      createdAt,
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取退款详情成功",
		"data":    result,
	}
	c.ServeJSON()
}

// Apply 申请退款
// @Title Apply Refund
// @Description 申请退款
// @Param	body	body	models.RefundApplyForm	true	"退款申请表单"
// @Success 200 {object} map[string]interface{}
// @router /apply [post]
func (c *RefundController) Apply() {
	// 解析请求参数
	var form struct {
		OrderNo string  `json:"order_no"`
		Amount  float64 `json:"amount"`
		Reason  string  `json:"reason"`
	}

	err := json.Unmarshal(c.Ctx.Input.RequestBody, &form)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if form.OrderNo == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单号不能为空",
		}
		c.ServeJSON()
		return
	}

	if form.Amount <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "退款金额必须大于0",
		}
		c.ServeJSON()
		return
	}

	if form.Reason == "" {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "退款原因不能为空",
		}
		c.ServeJSON()
		return
	}

	// 获取当前登录会员ID
	memberId := c.Ctx.Input.GetData("member_id").(int64)

	// 查询订单信息
	order, err := models.GetOrderByOrderNo(form.OrderNo)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "订单不存在",
		}
		c.ServeJSON()
		return
	}

	// 验证订单是否属于当前会员
	if order.MemberId != memberId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作此订单",
		}
		c.ServeJSON()
		return
	}

	// 验证订单状态是否为已支付
	if order.Status != 1 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "只有已支付的订单才能申请退款",
		}
		c.ServeJSON()
		return
	}

	// 验证退款金额是否超过订单金额
	if int64(form.Amount) > order.PayAmount {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "退款金额不能超过订单支付金额",
		}
		c.ServeJSON()
		return
	}

	// 检查是否已存在退款申请
	existRefund, _ := models.GetRefundByOrderNo(form.OrderNo)
	if existRefund != nil && existRefund.Id > 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "该订单已存在退款申请",
		}
		c.ServeJSON()
		return
	}

	// 创建退款记录
	refund := &models.Refund{
		OrderNo:        form.OrderNo,
		MemberId:       memberId,
		Amount:         form.Amount,
		PaymentChannel: order.PaymentChannel,
		TransactionId:  order.TradeNo,
		Reason:         form.Reason,
		Status:         "pending", // 待审核
	}

	// 保存退款记录
	id, err := models.CreateRefund(refund)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "申请退款失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "申请退款成功，请等待审核",
		"data": map[string]interface{}{
			"id":       id,
			"refundNo": refund.RefundNo,
		},
	}
	c.ServeJSON()
}

// GetList 获取退款列表
// @Title Get Refund List
// @Description 获取退款列表
// @Param	page		query	int	false	"页码"
// @Param	pageSize	query	int	false	"每页数量"
// @Param	refundNo	query	string	false	"退款单号"
// @Param	orderNo		query	string	false	"订单号"
// @Param	username	query	string	false	"用户名"
// @Param	status		query	string	false	"退款状态"
// @Param	startTime	query	string	false	"开始时间"
// @Param	endTime		query	string	false	"结束时间"
// @Success 200 {object} map[string]interface{}
// @router / [get]
func (c *RefundController) GetList() {
	user, err := middleware.GetCurrentMember(c.Ctx)
	if err != nil || user == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "未授权访问",
		}
		c.ServeJSON()
		return
	}
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("pageSize", 10)

	// 构建过滤条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 退款单号
	if refundNo := c.GetString("refundNo"); refundNo != "" {
		filters["refund_no"] = refundNo
	}

	// 订单号
	if orderNo := c.GetString("orderNo"); orderNo != "" {
		filters["order_no"] = orderNo
	}

	// 用户名
	if username := c.GetString("username"); username != "" {
		filters["username"] = username
	}

	// 退款状态
	if status := c.GetString("status"); status != "" {
		filters["status"] = status
	}

	// 时间范围
	if startTime := c.GetString("startTime"); startTime != "" {
		t, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
		if err == nil {
			filters["start_time"] = t.Unix()
		}
	}

	if endTime := c.GetString("endTime"); endTime != "" {
		t, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
		if err == nil {
			filters["end_time"] = t.Unix()
		}
	}

	// 查询退款记录
	refunds, total, err := models.GetRefundList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取退款记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 构建返回数据
	result := make([]map[string]interface{}, 0)
	for _, refund := range refunds {
		// 获取会员信息
		member, err := models.GetMemberById(refund.MemberId, user.FranchiseId)
		username := ""
		if err == nil {
			username = member.Name
		}

		// 格式化时间
		createdAt := time.Unix(refund.CreatedAt, 0).Format("2006-01-02 15:04:05")
		auditTime := ""
		if refund.AuditTime > 0 {
			auditTime = time.Unix(refund.AuditTime, 0).Format("2006-01-02 15:04:05")
		}
		completionTime := ""
		if refund.CompletionTime > 0 {
			completionTime = time.Unix(refund.CompletionTime, 0).Format("2006-01-02 15:04:05")
		}

		item := map[string]interface{}{
			"id":             refund.Id,
			"refundNo":       refund.RefundNo,
			"orderNo":        refund.OrderNo,
			"memberId":       refund.MemberId,
			"username":       username,
			"amount":         refund.Amount,
			"paymentChannel": refund.PaymentChannel,
			"transactionId":  refund.TransactionId,
			"refundTradeNo":  refund.RefundTradeNo,
			"reason":         refund.Reason,
			"remark":         refund.Remark,
			"status":         refund.Status,
			"auditTime":      auditTime,
			"auditorId":      refund.AuditorId,
			"completionTime": completionTime,
			"createdAt":      createdAt,
		}
		result = append(result, item)
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取退款记录成功",
		"data":    result,
		"total":   total,
	}
	c.ServeJSON()
}
